from flask_cors import CORS, cross_origin

from routes.app import app
from DBService.User_Service import UserService
from flask import request,jsonify
from routes.app import app
from flask_login import login_user
from flask_login import login_required,current_user
@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,session_id')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS,HEAD')
    # 这里不能使用add方法，否则会出现 The 'Access-Control-Allow-Origin' header contains multiple values 的问题
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response
@app.route('/')
def hello_world():
    print("New request")
    return "New request, World!"

@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    user = UserService().get_user(username, password)
    if user is None:
        return jsonify({"error": "User not found"}), 404
    if not user.check_password_correction(password):
        return jsonify({"error": "Invalid password"}), 401
    login_user(user)
    user_dict= {
        "uid": user.uid,
        "username": user.username,
        "password": user.password,
        "created_at": user.created_at,
        "updated_at": user.updated_at
    }
    print(user_dict)

    return jsonify({"message": "Logged in successfully", "user": user_dict}), 200
@app.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    # Check if the username is already taken
    existing_user = UserService().get_user_by_username(username)
    if existing_user is not None:
        return jsonify({"error": "Username is already taken"}), 400

    # Check if the password is valid
    if len(password) < 8:
        return jsonify({"error": "Password must be at least 8 characters long"}), 400

    # Create the new user
    user = UserService().add_user(username, password)
    if user is None:
        return jsonify({"error": "Failed to create user"}), 500

    return jsonify({"message": "User registered successfully"}), 200
@app.route('/changePassword', methods=['POST'])
@login_required
def changePassword():
    data = request.get_json()
    old_password = data.get('old_password')
    new_password = data.get('new_password')
    user = UserService().get_user(current_user.username, old_password)
    if user is None:
        return jsonify({"error": "Invalid old password"}), 401
    UserService().update_user(user.uid, user.username, new_password)
    return jsonify({"message": "Password updated successfully"}), 200
@app.route('/logout')
@login_required
def logout():
    return jsonify({"message": "Logged out successfully"}), 200